package com.itzdm.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itzdm.reggie.common.constant.MessageConstant;
import com.itzdm.reggie.common.exception.DeletionNotAllowedException;
import com.itzdm.reggie.dto.DishDto;
import com.itzdm.reggie.entity.Category;
import com.itzdm.reggie.entity.Dish;
import com.itzdm.reggie.entity.DishFlavor;
import com.itzdm.reggie.entity.SetmealDish;
import com.itzdm.reggie.mapper.DishMapper;
import com.itzdm.reggie.service.CategoryService;
import com.itzdm.reggie.service.DishFlavorService;
import com.itzdm.reggie.service.DishService;
import com.itzdm.reggie.service.SetmealDishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 分页查询菜品
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public Page pageDish(Integer page, Integer pageSize, String name) {
        //分页参数
        Page<Dish> dishPage = new Page<>(page, pageSize);
        //进行名字的查询
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        //根据更新日期进行排序
        wrapper.orderByDesc(Dish::getUpdateTime);
        //进行分页查询
        page(dishPage, wrapper);
        //将Page<Dish>中的除了records中的属性拷贝到Page<DishDto>中
        Page<DishDto> dishDtoPage = new Page<>();
        BeanUtils.copyProperties(dishPage, dishDtoPage,"records");
        //将分页查询到的记录拿出进行处理
        List<Dish> records = dishPage.getRecords();

        List<DishDto> list = records.stream().map(item -> {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(item, dto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            dto.setCategoryName(category.getName());
            return dto;
        }).toList();
        //将处理好的记录放入Page中
        dishDtoPage.setRecords(list);
        return dishDtoPage;
    }

    /**
     * 新增菜品和口味
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithFlavors(DishDto dishDto) {
        //保存菜品
        save(dishDto);
        //保存口味表
        Long dishDtoId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map(item->{
            item.setDishId(dishDtoId);
            return item;
        }).toList();
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 启用或禁用菜品
     * @param ids
     * @param status
     */
    @Override
    // 根据ids和status更新菜品状态
    public void startOrStop(String ids, Integer status) {
        // 如果ids中不包含逗号
        if (!ids.contains(",")){
            // 根据id获取菜品
            Dish byId = getById(ids);
            // 设置菜品状态
            byId.setStatus(status);
            // 更新菜品
            updateById(byId);
            return;
        }
        // 如果ids中包含逗号，则分割ids
        String[] split = ids.split(",");
        // 遍历分割后的ids
        for (String id : split) {
            // 根据id获取菜品
            Dish byId = getById(id);
            // 设置菜品状态
            byId.setStatus(status);
            // 更新菜品
            updateById(byId);
        }
    }

    /**
     * 批量删除菜品接口
     * @param ids
     */
    @Override
    @Transactional
    public void deleteByIds(List<Long> ids) {
        //查询当前菜品是否起售中
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Dish::getId, ids);
        wrapper.eq(Dish::getStatus, 1);
        long count = count(wrapper);
        if (count > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //判断当前菜品是否绑定了套餐
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getDishId, ids);
        long count1 = setmealDishService.count(setmealDishLambdaQueryWrapper);
        if (count1 > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //如果没有抛出异常，删除菜品
        removeByIds(ids);
        //删除对应的口味表
        LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(DishFlavor::getDishId, ids);
        dishFlavorService.remove(wrapper1);
    }

    @Override
    public DishDto getByIdWithCate(Long id) {
        Dish dish = getById(id);
        DishDto dto = new DishDto();
        //拷贝其他属性至dto中
        BeanUtils.copyProperties(dish, dto);
        //进行条件构造
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> flavors = dishFlavorService.list(wrapper);
        //设置口味值
        dto.setFlavors(flavors);
        return dto;
    }

    /**
     * 修改菜品
     * @param dishDto
     */
    @Override
    public void updateWithFlavors(DishDto dishDto) {
        //更新基本信息
        updateById(dishDto);
        //将口味表删除
        Long dishDtoId = dishDto.getId();
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DishFlavor::getDishId, dishDtoId);
        dishFlavorService.remove(wrapper);
        //将新的口味表保存
        List<DishFlavor> flavors = dishDto.getFlavors();
        //遍历口味表，将 dishId 设置为更新后的 dishId
        flavors = flavors.stream().map(item->{
            item.setDishId(dishDtoId);
            return item;
        }).toList();
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public List<DishDto> getDishesByCategory(Dish dish) {
        // 根据菜品信息构建查询条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        // 添加菜品分类ID查询条件
        wrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId, dish.getCategoryId());
        // 按照排序和更新时间排序
        wrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        // 添加菜品状态查询条件
        wrapper.eq(Dish::getStatus,1);
        // 根据查询条件查询菜品
        List<Dish> list = list(wrapper);
        return list.stream().map(item -> {
            // 创建菜品DTO对象
            DishDto dto = new DishDto();
            // 复制菜品属性
            BeanUtils.copyProperties(item, dto);
            // 获取菜品分类ID
            Long categoryId = item.getCategoryId();
            // 根据菜品分类ID查询分类信息
            Category category = categoryService.getById(categoryId);
            // 如果分类不为空，则设置分类名称
            if (category != null) {
                dto.setCategoryName(category.getName());
            }
            // 获取菜品ID
            Long id = item.getId();
            // 根据菜品ID查询口味信息
            LambdaQueryWrapper<DishFlavor> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(DishFlavor::getDishId, id);
            List<DishFlavor> list1 = dishFlavorService.list(wrapper1);
            // 设置口味信息
            dto.setFlavors(list1);
            return dto;
        }).toList();
    }


}
